package com.example.jucdemo.synchdemo;

/**
 * @Author: Dijah
 * @Date: 2023/3/17 15:13
 * @Desc:
 * 场景：两个线程同时访问一个或两个对象的静态同步方法
 * 这个是安全的
 */
public class demo3 implements Runnable{

    static demo3 instance1 =  new demo3();
    static demo3 instance2 = new demo3();

    @Override
    public void run() {
        method();
    }

    //这个方式使用了 synchronized 修饰静态方法
    private synchronized static void method() {
        System.out.println("thread Name : " + Thread.currentThread().getName() + ",start");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("thread name : " + Thread.currentThread().getName() + ",end");
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(instance1);
        Thread thread2 = new Thread(instance2);

        thread1.start();
        thread2.start();

        while (thread1.isAlive() || thread2.isAlive()){

        }
        System.out.println("test over.");
    }
}
